package lxgorm

import (
	gormprocess "gitee.com/lxgow/lxmysql/gorm/common/process"
	gormredis "gitee.com/lxgow/lxmysql/gorm/common/redis"
)

// query
// 创建时间:下午2:25
// 创建人:lixu

func commonQuery(result interface{}, typeName string, b *dataParams) (exist bool, err error) {

	if b.cache.on {
		var _exist bool
		if b.cache.typeName == CACHE_TYPE_PROCESS {
			_exist, _ = gormprocess.Get(b.cache.name, &result)
		} else if b.cache.typeName == CACHE_TYPE_REDIS {
			_exist, _ = gormredis.Get(b.cache.name, &result)
		}
		if _exist {
			return
		}
	}

	defer func() {
		if b.cache.on {
			if b.cache.typeName == CACHE_TYPE_PROCESS {
				gormprocess.Set(b.cache.name, result, b.cache.ex)
			} else if b.cache.typeName == CACHE_TYPE_REDIS {
				_ = gormredis.Set(b.cache.name, result, b.cache.ex)
			}
			return
		}
	}()

	res := SelectDb(b.dbIndex).Table(b.tableName).Where(b.where)

	if b.orderBy != "" {
		res = res.Order(b.orderBy)
	}

	if b.field != "" {
		res = res.Select(b.field)
	}

	if b.limit != -100 {
		res = res.Limit(b.limit)
	}

	if b.offset != -100 {
		res = res.Offset(b.limit)
	}

	if b.group != "" {
		res = res.Group(b.group)
	}

	if b.debug {
		res = res.Debug()
	}

	switch typeName {
	case "Find":
		res = res.Find(&result)
		break
	case "First":
		res = res.First(&result)
		break
	case "Last":
		res = res.Last(&result)
		break
	case "Take":
		res = res.Take(&result)
		break
	}

	err = res.Error
	exist = TableExist(err)
	if err != nil && !exist {
		err = nil
	}

	return

}

// First 获取第一条记录（主键升序）
func (b *dataParams) First(result interface{}) (tableExist bool, err error) {
	tableExist, err = commonQuery(result, "Find", b)
	return
}

// Last 获取最后一条记录（主键降序）
func (b *dataParams) Last(result interface{}) (tableExist bool, err error) {
	tableExist, err = commonQuery(result, "Last", b)
	return
}

// Take 获取一条记录，没有指定排序字段
func (b *dataParams) Take(result interface{}) (tableExist bool, err error) {
	tableExist, err = commonQuery(result, "Last", b)
	return
}

// Find 1
func (b *dataParams) Find(result interface{}) (exist bool, err error) {
	exist, err = commonQuery(result, "Find", b)
	return
}
